#!/usr/bin/python
# Michael P. Reilly (C) 2012  All rights reserved

from pyerector import *
import release

Clean.files = InitDirs.files = ('build', 'dist')

versions = VariableSet(
    V('$Revision$', V('hg.version')),
    V('$RelNo$', release.number),
)

Compile.uptodates = (
    Uptodate(sources=('release.py',),
        destinations=FileIterator('build', recurse=True),
    ),
    MergeMapper('bin', pattern='*.py', recurse=True, destdir='build'),
    MergeMapper('man', pattern='*.man', recurse=True, destdir='build'),
    MergeMapper('bashcomp', pattern='*.comp', recurse=True, destdir='build')
)
Compile.tasks = (
    Tokenize(
        MergeMapper('bin', pattern='*.py', recurse=True, destdir='build'),
        tokenmap=versions
    ),
    Tokenize(
        MergeMapper('man', pattern='*.man', recurse=True, destdir='build'),
        tokenmap=versions
    ),
    Tokenize(
        MergeMapper('bashcomp', pattern='*.comp', recurse=True, destdir='build'),
        tokenmap=versions
    ),
)

def encodefile(filename):
    from base64 import b64encode
    return b64encode(open(filename, 'rb').read())

class GenInstall(Tokenize):
    files = ('install.py',)
    dest = 'dist'
    mapping = (
        ('$sshcmd_code$', normjoin('build', 'sshcmd.py')),
        ('$sshcmd_doc$', normjoin('build', 'sshcmd.man')),
        ('$svrfilter_code$', normjoin('build', 'svrfilter.py')),
        ('$svrfilter_doc$', normjoin('build', 'svrfilter.man')),
        ('$server_doc$', normjoin('build', 'server.man')),
        ('$sshcmd_comp$', normjoin('build', 'sshcmd.comp')),
        ('$svrfilter_comp$', normjoin('build', 'svrfilter.comp')),
    )
    def update_tokenmap(self):
        # add version info to the installer as well
        for n in versions:
            self.tokenmap[n] = versions[n]
        for (l, r) in self.mapping:
            self.tokenmap[l] = encodefile(r)

Packaging.uptodates = (
    IdentityMapper('build', recurse=True, destdir=normjoin('dist', 'install.py')),
)
Packaging.tasks = (
    GenInstall,
    Chmod(normjoin('dist', 'install.py'), mode=0755),
)

PyErector()
